using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace ddWindowsControlLibrary
{
    public partial class TextBoxNumeric : TextBox
    {
        public TextBoxNumeric()
        {            
            InitializeComponent();
        }

        private int min;
        public int Min 
        {
            get { return min; }
            set 
            {
                min=value;
            }
        }

        private int max;
        public int Max
        {
            get { return max; }
            set
            {
                max=value;
            }
        }

       
        public int Value
        {
            get {
                // this is only for if the text is still empty "" and min > 0
                if (base.Text=="")
                    return min;
                else
                    return Convert.ToInt32(base.Text); 
            
            }
        }

        
        private bool IsValid(string newText)
        {

            if (newText.Equals("")
                || newText.Equals(String.Empty))
                return true;

            try
            {
                int newValue = Convert.ToInt32(newText);
                if ((newValue > max) || (newValue < min)) return false;
            }
            catch
            {
                return false;
            }
            return true;

        }


        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            // assemble new text with new KeyStroke
            //	and pass to validation routine.

            // NOTES;
            //	1) Delete key is NOT passed here
            //	2) control passed here after ProcessCmdKey() is run

            char c = e.KeyChar;
            if (!Char.IsControl(c))	// not sure about this?? nothing in docs about what is Control char??
            {
                // prevent spaces
                if (c.ToString() == " ")
                {
                    e.Handled = true;
                    return;
                }

                string newText = base.Text.Substring(0, base.SelectionStart)
                    + c.ToString() + base.Text.Substring(base.SelectionStart + base.SelectionLength);

                if (!IsValid(newText))
                    e.Handled = true;
            }
            base.OnKeyPress(e);
           
        }

        protected override void OnLeave(EventArgs e)
        {
            // handle - and leading zeros input since KeyPress handler must allow this
            if (base.Text != "")
            {
                if (!IsValid(base.Text))
                    base.Text = "";
            }
            base.OnLeave(e);
        }
    }
}